package com.isoft.illustrationsdraw.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.isoft.illustrationsdraw.service.RedisTokenService;

@Service
public class RedisTokenServiceImpl implements RedisTokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    // 设置令牌并设置过期时间为 expirationTimeInSeconds 秒
    @Override
    public boolean saveToken(String token, long expirationTimeInSeconds) {
        try {
            ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
            // 保存令牌并设置过期时间
            valueOps.set(token, "valid", expirationTimeInSeconds, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Long getTokenExpirationAndDelete(String token) {
        try {
            // 检查令牌是否存在
            ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
            String value = valueOps.get(token);
            
            if (value != null) {
                // 获取剩余过期时间（秒）
                Long expirationTime = redisTemplate.getExpire(token, TimeUnit.SECONDS);
                
                // 删除令牌，确保被访问一次后立即失效
                redisTemplate.delete(token);
                
                // 返回剩余时间
                return expirationTime;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null; // 如果令牌不存在或已过期
    }
    
}
